package com.cap.dreamcircle.Utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.TextView;

import com.cap.dreamcircle.App.App;
import com.cap.dreamcircle.Consts.Constants;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author:liucxu 1.首先会检查本地是否有指定路径（该路径有项目根目录
 * +voice+网络路径的文件名组成）
 * 的音频文件
 * 2.如果存在，直接装载播放
 * 3.如果不存在，则异步播放网络音频
 */

public class MediaPlayerUtils {

    private ProgressDialog pd;
    private MediaPlayer player = null;
    private Handler handler = null;
    private static Context context;
    private static MediaPlayerUtils instance = null;
    //    private UpdateSeekBarThread updateSeekBarThread;
    private int playPosition;
    private String voiceUrl="";
//    private DownFile d;//断点续传的文件
//    private AbFileDownloader loader;

    private MediaPlayerUtils() {
    }

    public static MediaPlayerUtils getInstance(Context context) {
        if (instance == null) {
            MediaPlayerUtils.context = context;
            instance = new MediaPlayerUtils();
            TelephonyManager telephonyManager = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            telephonyManager.listen(new MyPhoneListener(),
                    PhoneStateListener.LISTEN_CALL_STATE);
        }
        return instance;
    }

    public void initCountDownPlayer(final String voiceUrl, final Handler handler, final String time, final TextView tv) {
//        // 如果sd卡能用，播放sd卡上的文件
        final File voice = new File(App.GetInstance().getVoiceDir()
                + FileUtils.getVoiceFileNameFromUrl(voiceUrl));
//        if (FileUtils.avaiableMedia()) {
        if (false) {
            if (!voice.exists()) {
                // 播放网络文件
                playNetVoiceWithCountDown(voiceUrl, time, tv);
                // 如果sd卡中没有，先下载
                downUrl(voiceUrl, voice);
            } else {
                try {
                    player = player == null ? new MediaPlayer() : player;
                    player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            UpdateVoiceTimeThread.getInstance(time, tv).stop();
                        }
                    });
                    player.setDataSource(voice.toString());
                    player.prepare();
                    player.start();
                    UpdateVoiceTimeThread.getInstance(time, tv).start();
                    Message msg = handler.obtainMessage();
                    msg.obj = player;
                    msg.what = Constants.VOICE_DOWN_OK;
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            playNetVoiceWithCountDown(voiceUrl, time, tv);
        }
    }


    private void playNetVoiceWithCountDown(final String voiceUrl, final String time, final TextView tv) {
        showProgress();
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                Uri uri = Uri.parse(voiceUrl);
                player = player == null ? MediaPlayer.create(context, uri)
                        : player;
                player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        // TODO Auto-generated method stub
                        UpdateVoiceTimeThread.getInstance(time, tv).stop();
                    }
                });
                player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        // TODO Auto-generated method stub
                        dissmissProgress();
                        player.start();
                        UpdateVoiceTimeThread.getInstance(time, tv).start();
                        Message msg = handler.obtainMessage();
                        msg.obj = player;
                        msg.what = Constants.VOICE_DOWN_OK;
                        handler.sendMessage(msg);
                    }
                });
            }
        }).start();

    }

    /**
     * 显示无边框透明的progressdialog
     */
    private void showProgress() {
//        pd = new CustomProgressDialog(context);
//        pd.setCanceledOnTouchOutside(false);
//        pd.show();
    }

    /**
     * 隐藏无边框透明的progressdialog
     */
    private void dissmissProgress() {
        if (pd == null) {
            return;
        }
        pd.dismiss();
    }

    public void releasePlayer() {
        if (player != null) {
            if (player.isPlaying()) {
                player.stop();
            }
            player.release();
            player = null;
        }
        if (pd != null) {
            pd.dismiss();
            pd = null;
        }
        context = null;
        instance = null;
//        if (updateSeekBarThread != null) {
//            handler.removeCallbacks(updateSeekBarThread);
//        }
    }

    /**
     * 只有电话来了之后才暂停音乐的播放
     */
    static class MyPhoneListener extends android.telephony.PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:// 电话来了
                    if (instance != null) {
                        instance.callIsComing();
                    }
                    break;
                case TelephonyManager.CALL_STATE_IDLE: // 通话结束
                    if (instance != null) {
                        instance.callIsDown();
                    }
                    break;
            }
        }
    }

    /**
     * 来电话了
     */
    public void callIsComing() {
        if (player.isPlaying()) {
            playPosition = player.getCurrentPosition();// 获得当前播放位置
            player.stop();
        }
    }

    /**
     * 通话结束
     */
    public void callIsDown() {
        if (playPosition > 0) {
            player.seekTo(playPosition);
            playPosition = 0;
        }
    }

    private void downUrl(String voiceUrl, File vioceFile) {
        InputStream in = null;
        FileOutputStream fileOutputStream = null;
        HttpURLConnection connection = null;
        String downFilePath = null;
        File file = null;
        try {
            if (!FileUtils.avaiableMedia()) {
                return;
            }

            URL mUrl = new URL(voiceUrl);
            connection = (HttpURLConnection) mUrl.openConnection();
            connection.connect();
            //获取文件名，下载文件
            file = vioceFile;
            downFilePath = file.getPath();
            if (!file.exists()) {
                file.createNewFile();
            } else {
                //文件已存在
                file.delete();
            }
            in = connection.getInputStream();
            fileOutputStream = new FileOutputStream(file);
            byte[] b = new byte[1024];
            int temp = 0;
            while ((temp = in.read(b)) != -1) {
                fileOutputStream.write(b, 0, temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Logger.i("\"有文件下载出错了,已删除\"");
            //检查文件大小,如果文件为0B说明网络不好没有下载成功，要将建立的空文件删除
            if (file != null) {
                file.delete();
            }
            file = null;
            downFilePath = null;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
